from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators.http import require_http_methods
from PIL import Image, ImageDraw
from .api.save import get_ip
import base64, json
import uuid
import pickle
import io


def index(request):
    # return HttpResponse("Hello, world. You're at the polls index.")
    context          = {}
    context['hello'] = 'Hello World!'
    return render(request, 'index.html', context)

def pix(request):
    # 生成图片
    image = Image.new('RGBA', (2, 2), (255, 255, 0, 0))
    draw = ImageDraw.Draw(image)
    # draw.text((50, 50), 'Hello, world!', fill=(0, 0, 0))
    # 将图片转换为二进制数据
    buffer = io.BytesIO()
    image.save(buffer, format='png')
    image_data = buffer.getvalue()
    return HttpResponse(image_data, content_type='image/png')

@require_http_methods(["GET"])
def script(request):
    ua = request.user_agent
    session = request.session.session_key
    if not session:
        request.session.pid = uuid.uuid4()
        request.session.save()
        session = request.session.session_key
    cust_ip = get_ip(request)
    client = "mobile" if ua.is_mobile else ("tablet" if ua.is_tablet else "pc")
    cust_ua = request.META['HTTP_USER_AGENT']
    cust_session = session
    cust_pay = request.GET.get("pay", "")

    script = """
       var o = window.lpmir = {
          //url: "http://127.0.0.1:8000/record/",
          url: "https://mir.longpean.com/record/",
          gc:function(){
            var keyValue = document.cookie.match('(^|;) ?_gentukey=([^;]*)(;|$)');
            var re= keyValue ? keyValue[2] : "";
            if(!re){
            }
            return re;
          },
          sc:function(expiresDays = null, path = '/', domain = '', secure = false){
            var cookieString = `_gentukey=${Math.floor(Math.random()*10000000000000000)}`;
            if (expiresDays) {
              const date = new Date();
              date.setTime(date.getTime() + (expiresDays * 24 * 60 * 60 * 1000)); // 计算过期时间（以天数为单位）
              cookieString += `; expires=${date.toUTCString()}`;
            }
            cookieString += `; path=${path}`;
            if (domain) {
              cookieString += `; domain=${domain}`;
            }
            if (secure) {
              cookieString += '; Secure'; // 如果是https网站，可以添加Secure属性以使cookie只能通过安全连接传输
            }
            document.cookie = cookieString;
          },
          send:function(ev){
            var pa = ev;
            var default_p = {
                uid: this.gc('PHPSESSID') , 
                ip: "%s",
                clt: "%s",
                ua:"%s",
                tg: "",
                ss: "%s",
                spid: String(this.gc('_gentukey')),
                st: document.domain,
                pg: window.location.pathname,
                e: 'load-page', 
                url: window.location.href, 
                cls: '', 
                c: "pay_method:%s", 
                t: Date.parse(new Date()), 
                x: '', 
                y: ''
            };
            var new_p = Object.assign({}, default_p, pa);
            var code = encodeURIComponent(btoa(JSON.stringify(new_p)))
            var ajax = new XMLHttpRequest();
            ajax.open('get',`${this.url}?${code}`);
            ajax.send();            
          },
          init(){
            this.send({
                uid: this.gc('PHPSESSID') , 
                tg: "",
                spid: String(this.gc('_gentukey')),
                st: document.domain,
                pg: window.location.pathname,
                e: 'load-page', 
                url: window.location.href, 
                cls: '', 
                t: Date.parse(new Date()), 
                x: '', 
                y: ''
            })
          }
        };
        var _gentukey = window.lpmir.gc();
        if(!_gentukey){window.lpmir.sc()}
        o.init();
        console.log("loadjs...ok")
    """ % (
        #    request.COOKIES.get('request_token'), 
           get_ip(request), 
           "mobile" if ua.is_mobile else ("tablet" if ua.is_tablet else "pc"),
           request.META['HTTP_USER_AGENT'],
           session,
           request.GET.get("pay", "")
        #    request.META.get('HTTP_HOST'),
        #    request.META.get('PATH_INFO')
        )
    return HttpResponse(script, content_type="application/javascript; charset=utf-8")
